var intervalID;
var update_entries_run = 0;
var check_interval = 60000;
var close_interval = 10000;
var profile_page;
var notification_page;
var timeouts= {};

$(function() {

    $.fn.messageClose = function() {
        $(this).fadeTo('fast', 0, function() {
            $(this).hide('fast', function() {
                var timeout = timeouts[$(this).attr('id')];
                if (timeout != undefined) clearTimeout(timeout);
                $(this).remove();
            });
        });
    };

    $.fn.messageCloseTimeout = function(interval) {
        var _this = $(this);
        timeouts[_this.attr('id')] = setTimeout(function() {
            var close = _this.find('a.message_read');
            var link = close.attr('href');
            if (link != '#') $.ajax({url: link.replace('closed', 'read')});
            _this.messageClose();
        }, interval);
    };

    var elm_message = $("input#id_message");
    var elm_description = $("textarea#id_description");
    var elm_button = $("input#submit_button");
    var engage_login = $('div#engage_login');
    var picture_upload = $('#picture-upload')[0];

    $('a#details').click(function(event){
        event.preventDefault();
        $('div#more_details').toggle();
        $('div#upload_container').hide();
        var li_tab = $(this).parents('li.li-submit-tab');
        var has_class = li_tab.hasClass('active');
        $('li.li-submit-tab').removeClass('active');
        if (has_class) li_tab.removeClass('active');
        else li_tab.addClass('active');
    });

    $('a#picture').click(function(event){
        event.preventDefault();
        $('div#upload_container').toggle();
        $('div#more_details').hide();
        var li_tab = $(this).parents('li.li-submit-tab');
        var has_class = li_tab.hasClass('active');
        $('li.li-submit-tab').removeClass('active');
        if (has_class) li_tab.removeClass('active');
        else li_tab.addClass('active');
    });


    if (typeof(qq) != 'undefined' && picture_upload != undefined) {
        var upload = new qq.FileUploader({
        element: $('#picture-upload')[0],
        action: '/picture/upload/',
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
        sizeLimit: 5*1024*1024,
        minSizeLimit: 0,
        debug: false,
        onSubmit: function(id, fileName){
            $('div#picture-upload ul.qq-upload-list').empty();
            upload.setParams({ 'csrfmiddlewaretoken': csrf_token });
            $("input#submit_button").attr("disabled", true);
        },
        onComplete: function(id, fileName, responseJSON){
            if (responseJSON.error) {
                if (responseJSON.error == 'not_authenticated') {
                    this.showMessage('Please authenticate to upload image');
                }
                return false
            }
            check_length(elm_description, elm_message, elm_button);
            if (responseJSON.success) {
                var filename_small = responseJSON.success.filename.small;
                var filename_big = responseJSON.success.filename.big;
                var url = responseJSON.success.url;
            }
            if (filename_small === undefined || url === undefined || filename_big === undefined) return false;
            var image = '<img src="' + url +'"/>';
            var hidden_small = '<input type="hidden" name="picture_small" class="picture_ajax" value="'
                    + filename_small + '">';
            var hidden_big = '<input type="hidden" name="picture_big" class="picture_ajax" value="'
                    + filename_big + '">';
            $('div.more_details_picture').html(image).show();
            $('form#submit_form input.picture_ajax').remove();
            $('form#submit_form').append(hidden_small);
            $('form#submit_form').append(hidden_big);
        },
        showMessage: function(message){
            items_alert(message);
        },
        messages: {
            typeError: "image processing failed. Make sure its gif or jpg or png and up to 3MB.",
            sizeError: "image processing failed. Make sure its gif or jpg or png and up to 3MB.",
            minSizeError: "image processing failed. Make sure its gif or jpg or png and up to 3MB.",
            emptyError: "image processing failed. Make sure its gif or jpg or png and up to 3MB."
        }
    });
    }

    $(".qq-upload-button").contents().first().replaceWith("Click here to choose an image");

    elm_message.keyup(function(event){
        check_length(elm_description, elm_message, elm_button);
    });

    elm_description.keyup(function(event){
        check_length(elm_description, elm_message, elm_button);
    });

    $('input.comment_text').live('keyup', function(event){
        var button = $(this).parent().find('input.comment_button');
        var message_length = $(this).val().length;
        if (message_length > 0 && message_length <=256) {
            button.attr("disabled", false);
        } else {
            button.attr("disabled", true);
        }
    });

    $('textarea.twitter_message').live('keyup', function(event){
        var button = $(this).parents('div.twitter_share').find('input.twitter_button');
        var counter = $(this).parents('div.twitter_share').find('span.counter');
        var message_length = $(this).val().length;
        counter.text(message_length);
        if (message_length > 0 && message_length <=140) {
            button.attr("disabled", false);
        } else {
            button.attr("disabled", true);
        }
    });

    $('a.comments, a.airtime, a.share').live('click', function(event){
        event.preventDefault();
        var id = $(this).attr('href');
        $(this).parents('div.item').find('div.hidden_actions').each(function(){
            if ($(this).attr('id') != id.substring(1)) $(this).hide();
        });
        $('div'+id).toggle();
    });

    $('a.responses').live('click', function(event){
        event.preventDefault();
        var id = $(this).attr('href');
        var comment = $('div'+id).parents('div.comment_div');
        comment.show();
        $('div'+id).toggle();
        if ($('div'+id).is(':visible')) {
            $(this).parents('div.item').find('div.hidden_actions').hide();
            comment.show();
        } else {
            comment.hide();
        }
    });

    $('a.facebook_share, a.twitter_tweet, a.follow_link').live('click', function(event){
        event.preventDefault();
        var id = $(this).attr('href');
        var div = $('div#'+id);
        hide_popups(div);
        div.hide().fadeIn();
    });

    $('div.close').live('click', function(){
        engage_login.hide();
    });

    $('div.temp_message_close').live('click', function(){
            $(this).parent('li').remove();
    });

    $('a.message_read').live('click', function(event){
        event.preventDefault();
        if ($(this).attr('href') != '#') {
            $.ajax({ url: $(this).attr('href') });
        }
        $(this).parent('li').messageClose();
    });

    $('div.facebook_close').live('click', function(){
        var parent = $(this).parents('div.facebook_share');
        parent.find('textarea.facebook_message').val('');
        parent.hide();
    });

    $('div.twitter_close').live('click', function(){
        var parent = $(this).parents('div.twitter_share');
        parent.hide();
    });

    $('div.follow_close').live('click', function(){
        var parent = $(this).parents('div.follow_user');
        parent.hide();
    });

    $('a.auth_required, input.auth_required').live('click', function(event){
        event.preventDefault();
        var position = $(this).offset();
        if (!$(this).hasClass('right')) {
            position.left -= engage_login.outerWidth() + 10;
        }
        var container_bottom = $('div#wrapper').offset().top + $('div#wrapper').outerHeight();
        var engage_bottom = position.top + engage_login.outerHeight();
        var diff = container_bottom-engage_bottom-70;
        position.top += diff < 0 ? diff : 20;
        engage_login.css(position);
        engage_login.hide().fadeIn();
    });

    $("input#submit_button").attr("disabled", true);
    $("input.comment_button").attr("disabled", true);

    $('form.comment_form').live('submit', function() {
        $(this).find('input.comment_button').attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            beforeSubmit: function(arr) {
                for (var i=0; i < arr.length; i++) {
                    if (!arr[i].value) {
                        alert('Please enter a comment');
                        return false;
                    }
                }
            },
            success: function(data) {
                parent.find('input.comment_text').val('');
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    return false;
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.comment_button').attr("disabled", true);
                    parent.find('div.responses').show();
                    parent.find('div.comment_div').show();
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot comment item');
                return false;
            }
        };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.like_form').live('submit', function() {
        var button = $(this).find('input.button_as_link');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    button.attr("disabled", false);
                    return false;
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.comment_button').attr("disabled", true);
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot like item');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.delete_form').live('submit', function() {
        var button = $(this).find('input.button_as_link');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            beforeSubmit: function() {
                if (!confirm("Are you sure you want to delete this item?")) return false;
            },
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    button.attr("disabled", false);
                    return false
                } else {
                    parent.remove();
                    if (data.story) window.location.replace("/live/popular/");
                }
            },
            error: function (){
                items_alert('Error: Cannot delete item');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.repost_form').live('submit', function() {
        var button = $(this).find('input.button_as_link');
        button.attr("disabled", true);
        var options = {
            dataType: 'json',
            beforeSubmit: function() {
                if (!confirm("Are you sure you want to re-post this item?")) return false;
            },
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.url !== undefined) {
                    button.attr("disabled", false);
                    window.location.replace(data.url);
                }
            },
            error: function (){
                items_alert('Error: Cannot re-post item');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.comment_delete_form').live('submit', function() {
        var button = $(this).find('input.comment_delete');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            beforeSubmit: function() {
                if (!confirm("Are you sure you want to delete this comment?")) return false;
            },
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    button.attr("disabled", false);
                    return false
                } else {
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.comment_button').attr("disabled", true);
                    parent.find('div.comment_div').show();
                    parent.find('div.responses').show();
                }
            },
            error: function (){
                items_alert('Error: Cannot delete comment');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.follow_form').live('submit', function() {
        var button = $(this).find('input.submit_button');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: '+ data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.comment_button').attr("disabled", true);
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot follow');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.user_follow_form').live('submit', function() {
        var button = $(this).find('input.submit_button');
        button.attr("disabled", true);
        var parent = $(this).parents('div.follow_item');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: '+ data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.item){
                    parent = $(data.item).replaceAll(parent);
                } else {
                    parent.remove();
                }
                if (data.following != undefined) $('#count_following').text(data.following);
                if (data.followers != undefined) $('#count_followers').text(data.followers);
            },
            error: function (){
                items_alert('Error: Cannot follow');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('#follow_form_right').live('submit', function() {
        var button = $(this).find('input.submit_button');
        button.attr("disabled", true);
        var parent = $('#my_items_right');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: '+ data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.item){
                    parent = $(data.item).replaceAll(parent);
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot follow');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('.follow_form_broadcaster').live('submit', function() {
        var button = $(this).find('input.submit_button');
        button.attr("disabled", true);
        var parent = $(this).parents('div.broadcaster_follow');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: '+ data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.item){
                    parent.html(data.item);
                }
            },
            error: function (){
                items_alert('Error: Cannot follow');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.airtime_form').live('submit', function() {
        var button = $(this).find('input.airtime_button');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: '+ data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.comment_button').attr("disabled", true);
                    update_airtimes(csrf_token);
                } else {
                    parent.remove();
                    update_airtimes(csrf_token);
                }
            },
            error: function (){
                items_alert('Error: Cannot add airtime to item');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.facebook_form').live('submit', function() {
        var button = $(this).find('input.facebook_button');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    button.attr("disabled", false);
                    return false
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.facebook_button').attr("disabled", true);
                    parent.find('input.comment_button').attr("disabled", true);
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot share item');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.twitter_form').live('submit', function() {
        var button = $(this).find('input.twitter_button');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            success: function(data) {
                button.attr("disabled", false);
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    return false
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.twitter_button').attr("disabled", true);
                    parent.find('input.comment_button').attr("disabled", true);
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot share item');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form.comment_like_form').live('submit', function() {
        var button = $(this).find('input.button_as_link');
        button.attr("disabled", true);
        var parent = $(this).parents('div.response');
        var options = {
            dataType: 'json',
            success: function(data) {
                button.attr("disabled", false);
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error);
                    return false
                } else if (data.item){
                    parent = $(data.item).replaceAll(parent);
                }
            },
            error: function (){
                items_alert('Error: Cannot like response');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('form#mobile_email').live('submit', function() {
        var button = $(this).find('input.submit_button');
        button.attr("disabled", true);
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                button.attr("disabled", false);
                if (data.error){
                    items_alert('Error: ' + data.error);
                    return false;
                } else if (data.success){
                    items_alert(data.success, 'info');
                }
            },
            error: function (){
                items_alert('Error: Cannot send mail');
                button.attr("disabled", false);
                return false;
            }
         };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('div.btn_less').live('click', function(){
        toggle_airtime(-1, $(this).parents('div.item'));
    });

    $('div.btn_more').live('click', function(){
        toggle_airtime(1, $(this).parents('div.item'));
    });

    $('a#more_news').live('click', function(event){
        event.preventDefault();
        var item_ids = get_items_ids();
        if (item_ids.length == 0) return;
        var items_container = $('div#items_container');
        var link_div = $(this).parent();
        var url = $(this).attr('href');
        if (!url) return false;
        var options = {
            url: url,
            data: {'items': item_ids},
            type: 'POST',
            headers: {'X-CSRFToken': csrf_token},
            dataType: 'json',
            success: function(data) {
                if (!data) return;
                if (data.error){
                    items_alert('Error: ' + data.error, parent);
                    return false
                } else if (data.item) {
                    items_container.append(data.item);
                    link_div.remove();
                }
            },
            error: function() {
                items_alert('Error: Cannot show more items', link_div);
            }
        };
        $.ajax(options);
    });

    $('a.restore_airtime').live('click', function(event){
        event.preventDefault();
        restore_airtime(csrf_token);
        var message_read = $(this).siblings('a.message_read');
        if (message_read.length > 0) message_read.trigger('click');
    });

    $('#messages').ajaxComplete(function(e, xhr, settings) {
        var contentType = xhr.getResponseHeader("Content-Type");
        if (contentType == "application/javascript" || contentType == "application/json") {
            var json = JSON.parse(xhr.responseText);
            $.each(json.django_messages, function (i, item) {
                if (!$('li#message-'+item.message_pk).length) addMessage(item);
            });
            if (json.unclosed_notifications != undefined) {
                var notify = json.unclosed_notifications;
                var span = $('span#notification_count');
                if (span.length) {
                    if (notify == 0) {
                        span.remove();
                    } else {
                        span.text(notify);
                    }
                } else if (notify != 0) {
                        $('#notification_link').append('<span id="notification_count">'+ notify + '</span>');
                }
            }
        }
    });

    $('a#more_responses').live('click', function(event){
        event.preventDefault();
        var url = $(this).attr('href');
        var parent = $('div.responses');
        var link_div = $('div#div_more_responses');
        var info = $('div#responses_end');
        var options = {
            url: url,
            dataType: 'json',
            success: function(data) {
                if (!data) return;
                if (data.error){
                    items_alert('Error: ' + data.error, parent);
                    return false
                } else if (data.item) {
                    link_div.remove();
                    info.remove();
                    parent.append(data.item);
                }
            },
            error: function() {
                items_alert('Error: Cannot show more items', parent);
            }
        };
        $.ajax(options);
    });

    $('form.question_form').live('submit', function() {
        var button = $(this).find('input.button_as_link');
        button.attr("disabled", true);
        var parent = $(this).parents('div.item');
        var options = {
            dataType: 'json',
            success: function(data) {
                if (!data) return false;
                if (data.error){
                    items_alert('Error: ' + data.error, parent);
                    return false;
                } else if (data.item){
                    var menu = parent.find('#navigate_subtabs');
                    parent = $(data.item).replaceAll(parent);
                    if (menu.length) parent.find('#control_block').html(menu);
                    parent.find('input.comment_button').attr("disabled", true);
                } else {
                    parent.remove();
                }
            },
            error: function (){
                items_alert('Error: Cannot comment item', parent);
                return false;
            }
        };
        $(this).ajaxSubmit(options);
        return false;
    });

    $('div#filter a').live('click', function(event){
        event.preventDefault();
        if ($(this).hasClass('active')) return false;
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        if ($(this).hasClass('world_link')) {
            $('#id_location option[value=""]').attr('selected', 'selected');
        }
        filter_items();
    });

    $('div#filter #id_location').live('change', function(){
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        if (!$('#id_location option:selected').val()) {
            $('a.world_link').addClass('active');
            $(this).removeClass('active');
        }
        filter_items();
    });

    $('li#focuson a').live('click', function(event){
        event.preventDefault();
        $('div#filter').toggle();
        $(this).find('div').toggle();
        $(this).toggleClass('active');
    });

    $('span.icon_more_dev_stories').live('click', function(){
        var stories = $('#dev-stories div.dev_stories_container');
        if (stories.length == 0) return false;
        var active = [];
        stories.each(function(index){
            if ($(this).is(':visible')) active.push(index+1);
        });
        if (active[active.length-1] == stories.length-1) {
            $('#dev-stories div.dev_footer').hide();
        }
        if (active[0] > 0) {
            $('#dev-stories div.dev_less').show();
        }
        stories.each(function(index){
            if ($.inArray(index, active) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    $('span.icon_more_broadcasters').live('click', function(){
        var stories = $('#top_broadcasters div.broadcaster_container');
        if (stories.length == 0) return false;
        var active = [];
        stories.each(function(index){
            if ($(this).is(':visible')) active.push(index+1);
        });
        if (active[active.length-1] == stories.length-1) {
            $('#top_broadcasters div.dev_footer').hide();
        }
        if (active[0] > 0) {
            $('#top_broadcasters div.dev_less').show();
        }
        stories.each(function(index){
            if ($.inArray(index, active) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    $('span.icon_less_dev_stories').live('click', function(){
        var stories = $('#dev-stories div.dev_stories_container');
        if (stories.length == 0) return false;
        var active = [];
        stories.each(function(index){
            if ($(this).is(':visible')) active.push(index-1);
        });
        if (active[active.length-1] < stories.length-1) {
            $('#dev-stories div.dev_footer').show();
        }
        if (active[0] == 0) {
            $('#dev-stories div.dev_less').hide();
        }
        stories.each(function(index){
            if ($.inArray(index, active) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    $('span.icon_less_broadcasters').live('click', function(){
        var stories = $('#top_broadcasters div.broadcaster_container');
        if (stories.length == 0) return false;
        var active = [];
        stories.each(function(index){
            if ($(this).is(':visible')) active.push(index-1);
        });
        if (active[active.length-1] < stories.length-1) {
            $('#top_broadcasters div.dev_footer').show();
        }
        if (active[0] == 0) {
            $('#top_broadcasters div.dev_less').hide();
        }
        stories.each(function(index){
            if ($.inArray(index, active) > -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

    var messages = $("#messages li");
    if (messages.length > 0 && notification_page == undefined) {
        messages.messageCloseTimeout(close_interval);
    }

});

function check_length(elm_description, elm_message, elm_button) {
    var description_length = elm_description.val().length;
    var message_length = elm_message.val().length;
    $('span#description_count').text(description_length);
    if (description_length <= 256 && message_length > 0 )  {
        elm_button.attr("disabled", false);
    } else {
        elm_button.attr("disabled", true);
    }
}

function items_alert(message, level) {
    level = level || 'error';
    $('<li class="'+ level + '">'+message+'</li>').prependTo($('ul#messages')).fadeOut(5000);
}

function toggle_airtime(step, parent){
    var amount = parseInt(parent.find('div.airtime_amount').html());
    var airtime_rest = parseInt(parent.find('input.airtime_current').val());
    if (isNaN(amount) || amount<=0 || isNaN(airtime_rest) || airtime_rest<=0 ) return;
    if (isNaN(step)) return;
    amount = amount + parseInt(step);
    if (amount<1) amount = 1;
    if (amount>airtime_rest) amount = airtime_rest;
    parent.find('div.airtime_amount').html(amount.toString());
    parent.find('input.airtime_count').val(amount.toString());
}

function check_running_update(csrf_token, from) {
    if ( update_entries_run > 0) {
        var watchClose = setInterval( function() {
            try {
                if ( update_entries_run <= 0) {
                    clearInterval(watchClose);
                    update_entries(csrf_token);
                }
            } catch (e) {}
        }, 200);
    } else {
        update_entries(csrf_token);
    }
}

function update_entries(csrf_token){
/* Update all entries on the page*/
    var item_ids = get_items_ids();
    var opened = get_items_opened();
    if (item_ids.length == 0) return;
    update_entries_run += 1;
    $.ajax({
        url: '/items/update/',
        data: {'items': item_ids},
        type: 'POST',
        dataType: 'json',
        headers: {'X-CSRFToken': csrf_token},
        success: function(data){
            if (!data) return;
            $.each(data.items, function(index, entry){
                var ids = entry.id.toString();
                removeFromArray(ids, item_ids);
                var div = $('div#'+ids);
                div.replaceWith(entry.body);
            });
            for (var ids in item_ids) {
                $('div#'+item_ids[ids]).remove();
            }
            show_items_opened(opened);
            clear_interval(csrf_token);
        },
        error: function(){
            clear_interval(csrf_token);
        }
    });
}

function restore_airtime(csrf_token){
    var span = $('span#airtime_count');
    $.ajax({
        url: '/user/restore_airtime',
        dataType: 'json',
        success: function(data){
            if (!data) return;
            if (data.error) {
                items_alert('Error: ' + data.error, $('ul#message'));
                return
            }
            update_airtimes(csrf_token);
        }
    });
}

function update_airtimes(csrf_token){
    var item_ids = get_items_ids();
    if (item_ids.length == 0) return;
    $.ajax({
        url: '/items/airtime/',
        data: {'items': item_ids},
        type: 'POST',
        dataType: 'json',
        headers: {'X-CSRFToken': csrf_token},
        success: function(data){
            if (!data) return;
            $.each(data.items, function(index, entry){
                var ids = entry.id.toString();
                $('div#'+ids+' input.airtime_current').val(entry.airtime);
                var count = entry.airtime > 0 ? 1 : 0;
                $('div#'+ids+' input.airtime_count').val(count);
                $('div#'+ids+' div.airtime_amount').html(count);
                var content;
                if (entry.airtime > 0) {
                    content = '<a class="airtime" href="#airtime'
                            + ids + '">Airtime<span class="plus">+</span></a>';
                } else {
                    content = '<span class="gray">Airtime</span>';
                }
                $('div#'+ids+' div.airtime').html(content);
            });
            set_airtime(data.user_airtime);
        }
    });
}

function get_items_ids(){
    var ids = [];
    $('div.item').each(function() {
        ids.push($(this).attr('id'));
    });
    return ids;
}

function get_items_opened(){
    var opened = {};
    $('div.item').each(function() {
        $(this).find('div.hidden_actions:visible, div.follow_user:visible').each(function(){
            var id = $(this).attr('id');
            if (id) opened[id] = $(this);
        });
    });
    return opened
}

function show_items_opened(opened){
    for (var id in opened) {
        $('#'+id).replaceWith(opened[id]);
    }
}

function removeFromArray(string, array){
    for(var i in array) {
        if(array[i].indexOf(string)>-1) array.splice(i, 1);
    }
    return array;
}

function clear_interval(csrf_token){
    update_entries_run -= 1;
    if (intervalID == undefined) return;
    clearInterval(intervalID);
    intervalID = setInterval(function() { check_running_update(csrf_token); }, check_interval);
}

function set_airtime(airtime){
    $('span#airtime_count').text(airtime.toString() + ' airtime' + (airtime > 1?'s':''));
}

function addMessage(item) {
    var close_link = item.link?'<a class="message_read" href="'+item.link+'"><div class="message_close"></div></a>':'<div class="temp_message_close"></div>';
    var message = $('<li id="message-'+item.message_pk+'" class="'+item.extra_tags+'">' + item.message + close_link + '</li>');
    if (!isNaN(item.close_timeout) && notification_page == undefined) {
        message.messageCloseTimeout(item.close_timeout);
    }
    $("#messages").append(message);
}

function get_search_url(){
    var category, user, country, chapter;
    try {
        category = parseInt($('a.category_link.active').attr('href').substring(1));
    } catch (e) {
        category = 0;
    }
    try {
        user = parseInt($('a.user_link.active').attr('href').substring(1));
    } catch (e) {
        user = 0;
    }
    if (category == undefined || isNaN(category)) category = 0;
    if (user == undefined || isNaN(user)) user = 0;
    country = $('select#id_location.active').val() || 'all';
    chapter = $('input#chapter').val() || '8live';
    return [ chapter, category, user, country ].join('/') + '/'
}

function filter_items() {
    var parent = $('div#items_container');
    var dev_items = $('#rightcolumn');
    var filter = $('div#filter');
    var url = '/items/filter/' + get_search_url();
    var options = {
        url: url,
        dataType: 'json',
        success: function(data) {
            if (!data) return;
            if (data.error){
                items_alert('Error: ' + data.error, filter);
                return false;
            }
            if (data.item) {
                parent.html(data.item);
                parent.find('input.comment_button').attr("disabled", true);
            }
            if (data.dev_items) {
                dev_items.html(data.dev_items);
            }
        },
        error: function() {
            items_alert('Error: Cannot filter items', filter);
        }
    };
    $.ajax(options);
}

function open_twitter_box(id){
    var link = $('a#twitter_share_'+id);
    if (link.length != 0) {
        $('div#share'+id).show();
        link.addClass('twitter_tweet');
        link.attr('href', '#twitter'+id);
        link.trigger('click');
    } else {
        window.location.reload();
    }
}

function open_facebook_box(id){
    var link = $('a#facebook_share_'+id);
    if (link.length != 0) {
        $('div#share'+id).show();
        link.addClass('facebook_share');
        link.attr('href', '#facebook'+id);
        link.trigger('click');
    } else {
        window.location.reload();
    }
}
function hide_popups(el){
    $('div.follow_user, div.twitter_share, div.facebook_share').each(function(){
        if ($(this).attr('id') != el.attr('id')) $(this).hide();
    })
}
